package com.itheima.reggie.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.constants.Constant;
import com.itheima.reggie.dto.DishDTO;
import com.itheima.reggie.dto.SetmealDTO;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author Jetwang
 * @version 1.0
 * @date 2022/4/12 10:26
 * DashController 菜品控制器
 */
@RestController
@Slf4j
@RequestMapping("dish")
public class DishController {
    private DishService dishService;
    private CategoryService categoryService;
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    public void setDishFlavorService(DishFlavorService dishFlavorService) {
        this.dishFlavorService = dishFlavorService;
    }

    @Autowired
    public void setCategoryService(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    @Autowired
    public void setDishService(DishService dishService) {
        this.dishService = dishService;
    }

    /**
     * 分页查询菜品
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("page")
    public R<Page> list(int page, int pageSize, @RequestParam(value = "name", required = false) String name) {
        log.info("page: {}, pageSize: {}, name: {}", page, pageSize, name);
        // 构造分页构造器
        Page<Dish> dishInfo = new Page<>(page, pageSize);
        // 添加过滤条件
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(!StringUtils.isBlank(name), Dish::getName, name);
        // 添加排序条件
        lqw.orderByDesc(Dish::getUpdateTime);
        dishService.page(dishInfo, lqw);
        List<Dish> dishList = dishInfo.getRecords();
        List<DishDTO> dishDTOList = new ArrayList<>();
        for (Dish dish : dishList) {
            DishDTO dishDTO = new DishDTO();
            BeanUtils.copyProperties(dish, dishDTO);
            dishDTOList.add(dishDTO);
        }
        dishDTOList = dishDTOList.stream().map(item -> {
            if (categoryService.getById(item.getCategoryId()) != null) {
                item.setCategoryName(categoryService.getById(item.getCategoryId()).getName());
            }
            return item;
        }).collect(Collectors.toList());
        Page<DishDTO> dishDTOInfo = new Page<>();
        BeanUtils.copyProperties(dishInfo, dishDTOInfo);
        dishDTOInfo.setRecords(dishDTOList);
        return R.success(dishDTOInfo);
    }


    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long[] ids) {
        log.info("要删除的菜品id: {}", ids);
        List<Long> idList = Arrays.asList(ids);
        dishService.removeByIds(idList);
        return R.success("删除成功");
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDTO> getDishById(@PathVariable Long id) {
        log.info("要查询的菜品id: {}", id);
        Dish dish = dishService.getById(id);
        Long dishId = dish.getId();
        QueryWrapper<DishFlavor> qw = new QueryWrapper<>();
        qw.eq("dish_id", dishId);
        List<DishFlavor> dishFlavors = dishFlavorService.list(qw);
        DishDTO dishDTO = new DishDTO();
        BeanUtils.copyProperties(dish, dishDTO);
        dishDTO.setFlavors(dishFlavors);
        return R.success(dishDTO);
    }

    /**
     * 根据ids更新菜品
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status,@RequestParam("ids") Long[] ids) {
        log.info("要更新的菜品id为: {}", ids);
        List<Long> idList = Arrays.asList(ids);
        dishService.updateStatusByIds(status, idList);
        return R.success("更新成功");
    }


    /**
     * 新增菜品
     * @param dishDTO
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDTO dishDTO) {
        log.info("新增菜品: {}", dishDTO);
        dishService.saveWithFlavor(dishDTO);
        // 删除缓存数据
        redisTemplate.delete(Constant.CACHE_DISH + dishDTO.getCategoryId());
        return R.success("新增菜品成功");
    }

    /**
     * 更新菜品
     * @param dishDTO
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDTO dishDTO) {
        log.info("更新菜品: {}", dishDTO);
        dishService.updateWithFlavor(dishDTO);
        // 删除缓存数据
        redisTemplate.delete(Constant.CACHE_DISH + dishDTO.getCategoryId());
        return R.success("更新成功");
    }

    /**
     * 根据分类id查找菜品
     * @param categoryId
     * @return
     */
    @GetMapping("list")
    public R<List<Dish>> list(Long categoryId) {
        log.info("查询的分类id: {}", categoryId);
        // 先从缓存中查看该分类有无数据
        List<Dish> dishList = (List<Dish>) redisTemplate.opsForValue().get(Constant.CACHE_DISH + categoryId);
        if (dishList != null) {
            // 有数据则直接返回
            return R.success(dishList);
        }
        // 无数据则查询数据库
        // 创建构造条件
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getCategoryId, categoryId);
        // 状态为1
        lqw.eq(Dish::getStatus, 1);
        // 根据价格进行升序
        lqw.orderByAsc(Dish::getPrice);
        List<Dish> dishes = dishService.list(lqw);
        // 将数据存入缓存
        redisTemplate.opsForValue().set(Constant.CACHE_DISH + categoryId, dishes, 30L, TimeUnit.MINUTES);
        return R.success(dishes);
    }
}
